import { useQuery } from '@apollo/client'
import { useLocation, useNavigate } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { addUser } from '@/action/addUser'
import { GET_USER } from '@/graphql/user'
import { IUser } from '@/utils/types'

type IUser = typeof IUser

export const useGetUser = () => {
  const dispatch = useDispatch()
  const nav = useNavigate()
  const location = useLocation()
  const { loading, refetch } = useQuery<{ getUserInfo: IUser }>(GET_USER, {
    onCompleted: (data) => {
      if (data.getUserInfo) {
        const {
          id, name, tel, desc, avatar,
        } = data.getUserInfo
        // 登录成功，添加用户信息到 redux 中
        dispatch(addUser({
          id, name, tel, desc, avatar, refetchHandler: refetch,
        }))
        // 当前在登录页面，且已经登录了，那就直接跳到首页
        if (location.pathname === '/login') {
          nav('/')
        }
        return
      }
      dispatch(addUser({ refetchHandler: refetch }))
      // 如果不在登录页面，但是目前没有登录，那就直接跳到登录页面
      if (location.pathname !== '/login') {
        nav(`/login?orgUrl=${location.pathname}`)
      }
    },
    onError: () => {
      dispatch(addUser({ refetchHandler: refetch }))
      // 如果不在登录页面，但是目前登录异常，那就直接跳到登录页面
      if (location.pathname !== '/login') {
        nav(`/login?orgUrl=${location.pathname}`)
      }
    },
  })

  return { loading }
}
